package com.runa.monitor.platinterface.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhuj
 */
@Configuration
public class ExecutorConfig  {

    @Value("${scheduler.size.businessRequest:}")
    private Integer schedulerSize;

    /**
     * 请求业务线程池
     * 该线程池为试验性设参，将根据线上实际情况开辟大量线程
     * 根据试验结果确定是否如此使用
     */
    @Bean(name = "asyncRequestScheduler")
    public Executor asyncRequestScheduler() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        int prs = schedulerSize == null ? Runtime.getRuntime().availableProcessors() * 2 : schedulerSize;
        executor.setCorePoolSize(prs);
        AtomicInteger i= new AtomicInteger();
        executor.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName("business-async-request-"+ i.getAndIncrement());
            thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
            return thread;
        });
        //配置最大线程数
        executor.setMaxPoolSize(executor.getCorePoolSize() * 2);
        //配置队列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("business-async-request-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        //CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        //Discard_Oldest: 丢弃旧的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

    /**
     * 响应业务线程池
     */
    @Bean
    public Executor asyncResponseScheduler() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        AtomicInteger i= new AtomicInteger();
        executor.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName("business-async-response-"+ i.getAndIncrement());
            thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
            return thread;
        });
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setMaxPoolSize(executor.getCorePoolSize());
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setThreadNamePrefix("business-async-response-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * mqtt消息处理线程池
     */
    @Bean
    public Executor mqttResponseScheduler() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        AtomicInteger i= new AtomicInteger();
        executor.setThreadFactory(r -> {
            Thread thread = new Thread(r);
            thread.setName("mqtt-async-response-"+ i.getAndIncrement());
            thread.setUncaughtExceptionHandler(new CustomThreadUncaughtExceptionHandler());
            return thread;
        });
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setMaxPoolSize(executor.getCorePoolSize());
        executor.setQueueCapacity(Integer.MAX_VALUE);
        executor.setThreadNamePrefix("mqtt-async-response-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.initialize();
        return executor;
    }

}
